﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Text.RegularExpressions;
using System.Security.Permissions;

namespace BugTracker.InfoBox
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class InfoBoxDesigner : ControlDesigner
    {
        public override string GetDesignTimeHtml()
        {
            System.Reflection.Assembly l_asm = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream l_css_res = l_asm.GetManifestResourceStream("BugTracker.InfoBox.Resources.infobox.css");
            System.IO.StreamReader l_stream = new System.IO.StreamReader(l_css_res);
            string ls_css = l_stream.ReadToEnd();

            const string SUBSTITUTION_PATTERN = @"(<%=)\s*(WebResource\("")(?<resourceName>.+)\s*(""\)%>)";
            Regex theRegex = new Regex(SUBSTITUTION_PATTERN);
            ls_css = theRegex.Replace(ls_css, new MatchEvaluator(PerformSubstitution));

            return "<style>" + ls_css + "</style>" + base.GetDesignTimeHtml();
        }

        private string PerformSubstitution(Match m)
        {
            BugTracker.InfoBox.InfoBox thisWeightControl = (BugTracker.InfoBox.InfoBox)Component;
            string replacedString = m.ToString();
            replacedString = replacedString.Replace(m.Value, thisWeightControl.Page.ClientScript.GetWebResourceUrl(this.GetType(), m.Groups["resourceName"].Value));
            return replacedString;
        }
    }
}
